﻿namespace FredCK.FCKeditorV2.FileBrowser
{
    using FredCK.FCKeditorV2;
    using System;
    using System.Drawing;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;

    public abstract class FileWorkerBase : Page
    {
        public FredCK.FCKeditorV2.FileBrowser.Config Config;
        /// <summary>
        /// 系统属性逻辑类
        /// </summary>
        private ElingOA6_Admin_DSJCJ.BLL.Entity entityBLL=new ElingOA6_Admin_DSJCJ.BLL.Entity();
       
        protected FileWorkerBase()
        {
        }

        public void addWater(string sFilePath, ref string sFileName, HttpPostedFile oFile, string sExtension, string sServerDir)
        {
            string entityNo= System.Configuration.ConfigurationManager.AppSettings["EntityNo"];;
            Image image = Image.FromFile(sFilePath);
            if (base.Request.Params["R1"] == "V1")
            {
                Graphics graphics = Graphics.FromImage(image);
                graphics.DrawImage(image, 0, 0, image.Width, image.Height);
                Font font = new Font("宋体", 20f, GraphicsUnit.Pixel);
                Brush brush = new SolidBrush(Color.White);

                ElingOA6_Admin_DSJCJ.Model.Entity entityNoModel = entityBLL.GetModel(entityNo);
                if (entityNoModel != null)
                {
                    string text = entityNoModel.FTxtWaterMark;
                    SizeF ef = graphics.MeasureString(text, font);
                    float width = ef.Width;
                    float height = ef.Height;
                    graphics.DrawString(text, font, brush, (float)(image.Width - width), (float)(image.Height - height));
                    graphics.Dispose();
                }
            }
            if (base.Request.Params["R1"] == "V2")
            {
                string path = DAL.getWaterImg();
                Image image2 = Image.FromFile(base.Server.MapPath(path));
                Graphics graphics2 = Graphics.FromImage(image);
                graphics2.DrawImage(image2, new Rectangle(image.Width - image2.Width, image.Height - image2.Height, image2.Width, image2.Height), 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel);
                graphics2.Dispose();
            }
            sFileName = Path.GetFileNameWithoutExtension(oFile.FileName);
            string str3 = DAL.GenerateStringId() + "." + sExtension;
            sFileName = str3;
            str3 = Path.Combine(sServerDir, str3);
            image.Save(str3);
            image.Dispose();
            if (File.Exists(sFilePath))
            {
                File.Delete(sFilePath);
            }
        }

        private bool CheckNonHtmlFile(HttpPostedFile file)
        {
            byte[] buffer = new byte[0x400];
            file.InputStream.Read(buffer, 0, 0x400);
            string input = Encoding.ASCII.GetString(buffer);
            if (Regex.IsMatch(input, @"<!DOCTYPE\W*X?HTML", RegexOptions.Singleline | RegexOptions.IgnoreCase))
            {
                return false;
            }
            if (Regex.IsMatch(input, "<(?:body|head|html|img|pre|script|table|title)", RegexOptions.Singleline | RegexOptions.IgnoreCase))
            {
                return false;
            }
            if (Regex.IsMatch(input, "type\\s*=\\s*[\\'\"]?\\s*(?:\\w*/)?(?:ecma|java)", RegexOptions.Singleline | RegexOptions.IgnoreCase))
            {
                return false;
            }
            if (Regex.IsMatch(input, "(?:href|src|data)\\s*=\\s*[\\'\"]?\\s*(?:ecma|java)script:", RegexOptions.Singleline | RegexOptions.IgnoreCase))
            {
                return false;
            }
            if (Regex.IsMatch(input, "url\\s*\\(\\s*[\\'\"]?\\s*(?:ecma|java)script:", RegexOptions.Singleline | RegexOptions.IgnoreCase))
            {
                return false;
            }
            return true;
        }

        protected void FileUpload(string resourceType, string currentFolder, bool isQuickUpload)
        {
            HttpPostedFile file = base.Request.Files["NewFile"];
            string fileName = "";
            if (file == null)
            {
                this.SendFileUploadResponse(0xca, isQuickUpload);
            }
            else
            {
                string str2 = this.ServerMapFolder(resourceType, currentFolder, isQuickUpload);
                fileName = Path.GetFileName(file.FileName);
                fileName = this.SanitizeFileName(fileName);
                if (file.ContentLength > 0xa00000)
                {
                    this.SendFileUploadResponse(800, isQuickUpload);
                }
                else
                {
                    string extension = Path.GetExtension(file.FileName).TrimStart(new char[] { '.' });
                    if (!this.Config.TypeConfig[resourceType].CheckIsAllowedExtension(extension))
                    {
                        this.SendFileUploadResponse(0xca, isQuickUpload);
                    }
                    else if (this.Config.CheckIsNonHtmlExtension(extension) && !this.CheckNonHtmlFile(file))
                    {
                        this.SendFileUploadResponse(0xca, isQuickUpload);
                    }
                    else
                    {
                        string str5;
                        int errorNumber = 0;
                        int num2 = 0;
                        while (true)
                        {
                            fileName = DAL.GenerateStringId() + "." + extension;
                            str5 = Path.Combine(str2, fileName);
                            if (!File.Exists(str5))
                            {
                                break;
                            }
                            num2++;
                            fileName = string.Concat(new object[] { Path.GetFileNameWithoutExtension(file.FileName), "(", num2, ").", extension });
                            errorNumber = 0xc9;
                        }
                        file.SaveAs(str5);
                        string originalImagePath = str5;
                        try
                        {
                            if (base.Request.Params["C1"] == "ON")
                            {
                                this.addWater(str5, ref fileName, file, extension, str2);
                                originalImagePath = Path.Combine(str2, fileName);
                            }
                        }
                        catch
                        {
                            this.SendFileUploadResponse(0x332, isQuickUpload);
                        }
                        TypeConfig config = this.Config.TypeConfig[resourceType];
                        string fileUrl = isQuickUpload ? config.GetQuickUploadPath() : config.GetFilesPath();

                        if (((this.Config.MaxWidthOfUploadedImg > 0) && (resourceType == "Image")) && (extension.ToLower() != "gif"))
                        {
                            this.MakeThumbnail(originalImagePath, this.Config.MaxWidthOfUploadedImg);
                        }


                        fileUrl = fileUrl + fileName;
                        this.SendFileUploadResponse(errorNumber, isQuickUpload, fileUrl, fileName);
                    }
                }
            }
        }

        private string SanitizeFileName(string fileName)
        {
            if (this.Config.ForceSingleExtension)
            {
                fileName = Regex.Replace(fileName, @"\.(?![^.]*$)", "_", RegexOptions.None);
            }
            return Regex.Replace(fileName, "[\\\\/|:?*\"<>\\p{C}]", "_", RegexOptions.None);
        }

        protected string SanitizeFolderName(string folderName)
        {
            return Regex.Replace(folderName, "[.\\\\/|:?*\"<>\\p{C}]", "_", RegexOptions.None);
        }

        private void SendFileUploadResponse(int errorNumber, bool isQuickUpload)
        {
            this.SendFileUploadResponse(errorNumber, isQuickUpload, "", "", "");
        }

        private void SendFileUploadResponse(int errorNumber, bool isQuickUpload, string fileUrl, string fileName)
        {
            this.SendFileUploadResponse(errorNumber, isQuickUpload, fileUrl, fileName, "");
        }

        protected void SendFileUploadResponse(int errorNumber, bool isQuickUpload, string fileUrl, string fileName, string customMsg)
        {
            base.Response.Clear();
            base.Response.Write("<script type=\"text/javascript\">");
            base.Response.Write(@"(function(){var d=document.domain;while (true){try{var A=window.top.opener.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{}catch (e){break;}}})();");
            if (isQuickUpload)
            {
                base.Response.Write(string.Concat(new object[] { "window.parent.OnUploadCompleted(", errorNumber, ",'", fileUrl.Replace("'", @"\'"), "','", fileName.Replace("'", @"\'"), "','", customMsg.Replace("'", @"\'"), "') ;" }));
            }
            else
            {
                base.Response.Write(string.Concat(new object[] { "window.parent.frames['frmUpload'].OnUploadCompleted(", errorNumber, ",'", fileName.Replace("'", @"\'"), "') ;" }));
            }
            base.Response.Write("</script>");
            base.Response.End();
        }

        protected string ServerMapFolder(string resourceType, string folderPath, bool isQuickUpload)
        {
            TypeConfig config = this.Config.TypeConfig[resourceType];
            string path = isQuickUpload ? config.GetQuickUploadDirectory() : config.GetFilesDirectory();
            FredCK.FCKeditorV2.Util.CreateDirectory(path);
            return Path.Combine(path, folderPath.TrimStart(new char[] { '/' }));
        }
        public void MakeThumbnail(string originalImagePath, int maxWidth)
        {
            if (File.Exists(originalImagePath))
            {
                string destFileName = originalImagePath + "Temp";
                File.Move(originalImagePath, destFileName);
                Image image = Image.FromFile(destFileName);
                int width = image.Width;
                int height = image.Height;
                int x = 0;
                int y = 0;
                int num5 = image.Width;
                int num6 = image.Height;
                if (image.Width > maxWidth)
                {
                    width = maxWidth;
                    height = (image.Height * maxWidth) / image.Width;
                }
                Image image2 = new Bitmap(width, height);
                Graphics graphics = Graphics.FromImage(image2);
                graphics.InterpolationMode = InterpolationMode.High;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.Clear(Color.Transparent);
                graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(x, y, num5, num6), GraphicsUnit.Pixel);
                try
                {
                    image2.Save(originalImagePath, ImageFormat.Jpeg);
                }
                catch (Exception exception)
                {
                    this.SendFileUploadResponse(1, true, "", "", exception.ToString());
                }
                finally
                {
                    image.Dispose();
                    image2.Dispose();
                    graphics.Dispose();
                    File.Delete(destFileName);
                }
            }
            else
            {
                this.SendFileUploadResponse(1, true, "", "", "Original image not found");
            }
        }

 

 

    }
}

